export function loadScript(src: string) {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = src;
        script.onload = resolve;
        script.onerror = reject;
        script.id = "lessjs";
        document.head.appendChild(script);
    });
}

export function doChangeColor(hex, func = null) {

    const changeColor = () => {
        if (hex != null && hex !== 'null') {
            (window as any).less.modifyVars({
                '@primary-color': hex
            }).then(() => {
                localStorage.setItem('sms-theme', hex);
                window.scrollTo(0, 0);
                if (func) {
                    func();
                }
            })
            .catch((e) => {
                console.error(`加载自定义主题[${hex}]失败` + e);
                if (func) {
                    func();
                }
            });
        } else {
            if (func) {
                func();
            }
        }
    };

    const lessUrl = 'https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js';

    if (document.getElementById('lessjs')) {
        changeColor();
    } else {
        (window as any).less = {
            async: true
        };
        loadScript(lessUrl).then(() => {
            changeColor();
        });
    }
}

export function tryLoadLess() {
    if (!document.getElementById('lessjs')) {
        (window as any).less = {
            async: true
        };
        const lessUrl = 'https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js';
        return loadScript(lessUrl);
    }
    return new Promise((resolve, reject) => {
        resolve();
    })
}

export function tryLoadTheme() {
    return new Promise((resolve, reject) => {
        if (!document.getElementById('customtheme')) {
            const node = document.createElement('link');
            node.id = 'customtheme'
            node.rel = 'stylesheet/less';
            node.type = 'text/css';
            node.href = 'assets/theme.less';
            document.getElementsByTagName('head')[0].appendChild(node);
            resolve();
        } else {
            resolve();
        }
    })
}
